using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;

namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            IsMdiContainer = true;
        }

        private void openChildWindowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 使用反射创建子窗口实例
            CreateInstance("test.Form2", openChildWindowToolStripMenuItem);
        }

        void CreateInstance(string ClassName, ToolStripMenuItem sender)
        {
            Type type = Type.GetType(ClassName);
            Form frm = (Form)Activator.CreateInstance(type);
            frm.MdiParent = this;
            frm.Text = "学生管理系统";
            
            // 禁用当前菜单项
            if (sender is ToolStripMenuItem)
            {
                (sender as ToolStripMenuItem).Enabled = false;
            }
            
            // 显示子窗口
            frm.Show();
            
            // 创建窗口菜单项并添加到窗口菜单
            ToolStripMenuItem tsmi = new ToolStripMenuItem();
            windowToolStripMenuItem.DropDownItems.Add(tsmi);
            tsmi.Text = frm.Text;
            tsmi.Click += Tsmi_Click;
            
            // 双向引用，便于管理
            frm.Tag = tsmi;
            tsmi.Tag = frm;
            
            // 添加窗口关闭事件处理
            frm.FormClosed += Frm_FormClosed;
        }

        private void Frm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Form frm = (Form)sender;
            if (frm.Tag is ToolStripMenuItem)
            {
                ToolStripMenuItem tsmi = frm.Tag as ToolStripMenuItem;
                // 从窗口菜单中移除
                windowToolStripMenuItem.DropDownItems.Remove(tsmi);
            }
            
            // 重新启用打开子窗口菜单项
            openChildWindowToolStripMenuItem.Enabled = true;
        }

        private void Tsmi_Click(object sender, EventArgs e)
        {
            if (sender is ToolStripMenuItem)
            {
                ToolStripMenuItem tsmi = sender as ToolStripMenuItem;
                if (tsmi.Tag is Form)
                {
                    Form frm = tsmi.Tag as Form;
                    // 确保窗口不为空且未被释放
                    if (frm != null && !frm.IsDisposed)
                    {
                        // 激活窗口并设置为正常状态
                        frm.WindowState = FormWindowState.Normal;
                        frm.Activate();
                    }
                }
            }
        }
    }
}